package com.smm.web.mtower.bo;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.smm.web.mtower.domain.TagAlamEvent;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;

/**
 * Created by zhenghao on 2016/6/13.
 *
 */
@Service
public class RemoteBO {

    private Logger logger= Logger.getLogger(this.getClass());

    @Value("${remote.url}")
    private String remoteUrl;    //远程服务器访问地址

    @Value("${upload.image.url}")
    private String uploadImageUrl;  //图片上传地址


    public String getRemoteUrl() {
        return remoteUrl;
    }

    public void setRemoteUrl(String remoteUrl) {
        this.remoteUrl = remoteUrl;
    }


    public String getUploadImageUrl() {
        return uploadImageUrl;
    }

    public void setUploadImageUrl(String uploadImageUrl) {
        this.uploadImageUrl = uploadImageUrl;
    }

    /**
     * 上传报警事件
     * @param event
     */
    public void post(TagAlamEvent event) throws Exception {

        URL url = new URL(remoteUrl);

        System.out.println(remoteUrl);

        //打开连接
        HttpURLConnection con = (HttpURLConnection)url.openConnection();

        // 设置通用的请求属性
        con.setConnectTimeout(10*1000);    //设置超时时间 10 秒
        con.setRequestMethod("POST");
        con.setRequestProperty("accept", "*/*");
        con.setRequestProperty("connection", "Keep-Alive");
        con.setRequestProperty("user-agent","Mozilla/5.0");
        con.setDoOutput(true);
        con.setDoInput(true);


        //参数对象转换为 json 字符串
        String dataStr = new ObjectMapper().writeValueAsString(event);

        //发送数据
        dataStr = "data="+URLEncoder.encode(dataStr,"UTF-8");

        byte [] data = dataStr.getBytes();

        con.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
        con.setRequestProperty("Content-Lenth",String.valueOf(data.length));

        OutputStream out = con.getOutputStream();
        out.write(data);

        out.close();

        //获得服务器响应码
        int responseCode = con.getResponseCode();

        System.out.println(responseCode);

        //响应成功， 读取返回内容
        if(responseCode==200){

            InputStream  oin = con.getInputStream();

            String msg = changeInputStream(oin,"UTF-8");

            System.out.println(msg);

            oin.close();

        }else {

            logger.error("服务端响应失败。 code:"+responseCode);
        }


    }

    /**
     * 上传图片
     * @param imageFullPath 图片访问路径
     */
    public void uploadImage(String imageFullPath) throws Exception{

        File imageFile = new File(imageFullPath);

        if(!imageFile.exists()) throw new Exception("文件不存在");

        URL url = new URL(uploadImageUrl);

        System.out.println(uploadImageUrl);

        //打开连接
        HttpURLConnection con = (HttpURLConnection)url.openConnection();

        // 设置通用的请求属性
        con.setConnectTimeout(10*1000);    //设置超时时间 10 秒
        con.setRequestMethod("POST");
        con.setRequestProperty("accept", "*/*");
        con.setRequestProperty("connection", "Keep-Alive");
        con.setRequestProperty("user-agent","Mozilla/5.0");
        con.setDoOutput(true);
        con.setDoInput(true);

        String BOUNDARY = "----------" + System.currentTimeMillis();
        con.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY);


        // 第一部分：
        StringBuilder sb = new StringBuilder();
        sb.append("--"); // 必须多两道线
        sb.append(BOUNDARY);
        sb.append("\r\n");
        sb.append("Content-Disposition: form-data;name=\"file\";filename=\"" + imageFile.getName() + "\"\r\n");
        sb.append("Content-Type:application/octet-stream\r\n\r\n");
        byte[] head = sb.toString().getBytes("utf-8");

        // 获得输出流
        OutputStream out = new DataOutputStream(con.getOutputStream());
        // 输出表头
        out.write(head);

        //读取并发送文件
        // 文件正文部分
        // 把文件已流文件的方式 推入到url中
        FileInputStream fin = new FileInputStream(imageFile);

        int bytes = 0;
        byte[] bufferOut = new byte[1024];
        while ((bytes = fin.read(bufferOut)) != -1) {
            out.write(bufferOut, 0, bytes);
        }
        fin.close();
        // 结尾部分
        byte[] foot = ("\r\n--" + BOUNDARY + "--\r\n").getBytes("utf-8");// 定义最后数据分隔线
        out.write(foot);
        out.flush();
        out.close();

        //获得响应码
        int responseCode = con.getResponseCode();

        System.out.println(responseCode);

        //响应成功， 读取返回内容
        if(responseCode==200){

            InputStream  oin = con.getInputStream();

            String msg = changeInputStream(oin,"UTF-8");

            System.out.println(msg);

            oin.close();

        }else {

            logger.error("服务端响应失败。 code:"+responseCode);
        }


    }


    public static void main(String[] args) throws Exception {

        RemoteBO remoteBO = new RemoteBO();

//        remoteBO.setRemoteUrl("http://127.0.0.1:8080/monitor/alam/recive.do");
//
//        TagAlamEvent event = new TagAlamEvent("03000019");
//
//        event.setImageName("1465348716642.jpg");
//
//        remoteBO.post(event);

        remoteBO.setUploadImageUrl("http://127.0.0.1:8080/monitor/alam/reciveImage.do");

        remoteBO.uploadImage("D:/images/1465348716642.jpg");

    }


    public static String changeInputStream(InputStream inputStream,String encode) {

        // ByteArrayOutputStream 一般叫做内存流
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();

        byte[] data = new byte[1024];
        int len = 0;
        String result = "";

        if (inputStream != null) {

            try {
                while ((len = inputStream.read(data)) != -1) {
                    byteArrayOutputStream.write(data, 0, len);

                }

                result = new String(byteArrayOutputStream.toByteArray(), encode);

            } catch (IOException e) {
                e.printStackTrace();
            }

        }

        return result;
    }
}
